<template>
    <div class="question-edit-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>{{ id ? '编辑题目' : '新增题目' }}</span>
          <el-button  style="float: right; margin-left: 10px"  type="primary" @click="submitForm" :loading="submitting">保存</el-button>
          <el-button  style="float: right" @click="cancelEdit">取消</el-button>
        </div>
        <el-form ref="questionForm" :model="form" :rules="rules"  label-width="100px">
          <!-- 题目类型 -->
          <el-form-item label="题目类型" prop="type">
            <el-radio-group v-model="form.type" @change="handleTypeChange">
              <el-radio label="single">单选题</el-radio>
              <el-radio label="multiple">多选题</el-radio>
              <el-radio label="judgment">判断题</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题目内容 -->
          <el-form-item label="题目内容" prop="content">
            <el-input v-model="form.content" type="textarea" :rows="3" placeholder="请输入题目内容" clearable/>
          </el-form-item>
          <!-- 题目选项（判断题不显示） -->
          <el-form-item  label="题目选项" prop="options" v-if="form.type !== 'judgment'">
            <div class="options-list">
              <div  v-for="(option, index) in form.options" :key="index" class="option-item">
                <el-checkbox  v-model="option.isCorrect" :disabled="form.type === 'single' && hasOtherCorrect(index)">正确答案</el-checkbox>
                <el-input v-model="option.text" :placeholder="`选项 ${index + 1}`" style="width: 300px; margin: 0 10px;" clearable/>
                <el-button type="danger" circle icon="el-icon-delete" @click="removeOption(index)" :disabled="form.options.length <= 2"/>
              </div>
            </div>
            <el-button type="primary"  plain  icon="el-icon-plus" @click="addOption" :disabled="form.options.length >= 6">添加选项</el-button>
          </el-form-item>
          <!-- 判断题答案 -->
          <el-form-item label="正确答案" prop="judgmentAnswer" v-if="form.type === 'judgment'">
            <el-radio-group v-model="form.judgmentAnswer">
              <el-radio :label="true">正确</el-radio>
              <el-radio :label="false">错误</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度设置 -->
          <el-form-item label="题目难度" prop="difficulty">
            <el-rate v-model="form.difficulty" :max="5" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"/>
          </el-form-item>
  
          <!-- 答案解析 -->
          <el-form-item label="答案解析" prop="analysis">
            <el-input v-model="form.analysis" type="textarea" :rows="2" placeholder="请输入题目解析" clearable/>
          </el-form-item>
  
          <!-- 标签 -->
          <el-form-item label="题目标签">
            <el-tag
              v-for="tag in form.tagsArray"
              :key="tag"
              closable
              @close="removeTag(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="tagInputVisible"
              v-model="tagInputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="addTag"
              @blur="addTag"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showTagInput">+ 添加标签</el-button>
          </el-form-item>
  
          <!-- 状态 -->
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
            ></el-switch>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script>
  import { getQuestionDetail, saveQuestion } from '@/api/study-question'
  
  export default {
    name: 'QuestionEdit',
    data() {
      return {
        id: '',
        submitting: false,
        tagInputVisible: false,
        tagInputValue: '',
        form: {
          type: 'single',
          content: '',
          options: [
            { text: '', isCorrect: false },
            { text: '', isCorrect: false }
          ],
          judgmentAnswer: true,
          difficulty: 3,
          analysis: '',
          tags: '',
          tagsArray: [],
          status: 1
        },
        rules: {
          type: [{ required: true, message: '请选择题目类型', trigger: 'change' }],
          content: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
          options: [
            { 
              validator: this.validateOptions, 
              trigger: 'change' 
            }
          ],
          judgmentAnswer: [
            { required: true, message: '请选择判断题答案', trigger: 'change' }
          ],
          difficulty: [
            { required: true, message: '请设置题目难度', trigger: 'change' }
          ]
        }
      }
    },
    created() {
      var id = this.$route.params.id;
      this.id = id;
      if (this.id) {
        this.fetchQuestionDetail()
      }
    },
    methods: {
      // 获取题目详情
      async fetchQuestionDetail() {
        try {
          const res = await getQuestionDetail(this.id)
          const data = res.data
          console.log(data);
          this.form = {
            id: this.id,
            type: data.type,
            content: data.content,
            options: data.options || [],
            judgmentAnswer: data.judgmentAnswer !== undefined ? data.judgmentAnswer : true,
            difficulty: data.difficulty || 3,
            analysis: data.analysis || '',
            tags: data.tags || '',
            tagsArray: data.tags ? data.tags.split(',') : [],
            status: data.status
          }
        } catch (error) {
          console.error('获取题目详情失败:', error)
          this.$message.error('获取题目详情失败')
        }
      },
      
      // 添加选项
      addOption() {
        if (this.form.options.length >= 6) return
        this.form.options.push({ text: '', isCorrect: false })
      },
      
      // 删除选项
      removeOption(index) {
        if (this.form.options.length <= 2) return
        this.form.options.splice(index, 1)
      },
      
      // 检查是否有其他正确答案(用于单选题)
      hasOtherCorrect(currentIndex) {
        return this.form.options.some((opt, idx) => idx !== currentIndex && opt.isCorrect)
      },
      
      // 验证选项
      validateOptions(rule, value, callback) {
        if (this.form.type === 'judgment') {
          callback()
          return
        }
        
        // 检查是否有正确答案
        const hasCorrect = this.form.options.some(opt => opt.isCorrect)
        if (!hasCorrect) {
          callback(new Error('请至少设置一个正确答案'))
          return
        }
        
        // 检查单选题只能有一个正确答案
        if (this.form.type === 'single' && 
            this.form.options.filter(opt => opt.isCorrect).length > 1) {
          callback(new Error('单选题只能有一个正确答案'))
          return
        }
        
        // 检查选项内容是否为空
        const hasEmpty = this.form.options.some(opt => !opt.text.trim())
        if (hasEmpty) {
          callback(new Error('选项内容不能为空'))
          return
        }
        
        callback()
      },
      
      // 题目类型变化
      handleTypeChange(type) {
        if (type === 'judgment') {
          this.form.options = []
        } else if (this.form.options.length < 2) {
          this.form.options = [
            { text: '', isCorrect: false },
            { text: '', isCorrect: false }
          ]
        }
      },
      
      // 添加标签
      addTag() {
        const inputValue = this.tagInputValue.trim()
        if (inputValue && !this.form.tagsArray.includes(inputValue)) {
          this.form.tagsArray.push(inputValue)
          this.form.tags = this.form.tagsArray.join(',')
        }
        this.tagInputVisible = false
        this.tagInputValue = ''
      },
      
      // 移除标签
      removeTag(tag) {
        this.form.tagsArray = this.form.tagsArray.filter(t => t !== tag)
        this.form.tags = this.form.tagsArray.join(',')
      },
      
      // 显示标签输入框
      showTagInput() {
        this.tagInputVisible = true
        this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      
      // 提交表单
      async submitForm() {
        this.$refs.questionForm.validate(async valid => {
          if (!valid) {
            return this.$message.warning('请完善题目信息')
          }
          try {
            this.submitting = true
            // 准备提交数据
            const formData = { 
              ...this.form,
              tags: this.form.tagsArray.join(',')
            }
            if (this.form.type === 'judgment') {
              // 判断题不需要options字段
              delete formData.options
            } else {
              // 其他类型不需要judgmentAnswer字段
              delete formData.judgmentAnswer
            }
            // 调用API保存题目
            await saveQuestion(formData)
            this.$message.success('题目保存成功')
            this.$emit('success')
            this.cancelEdit()
          } catch (error) {
            console.error('保存题目失败:', error)
            this.$message.error('保存题目失败: ' + (error.message || '服务器错误'))
          } finally {
            this.submitting = false
          }
        })
      },
      
      // 取消编辑
      cancelEdit() {
        this.$router.push('/study/question/list')
      }
    }
  }
  </script>
  
  <style scoped>
  .question-edit-container {
    padding: 20px;
  }
  
  .options-list {
    margin-bottom: 15px;
  }
  
  .option-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .el-tag {
    margin-right: 10px;
  }
  
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  </style>